package com.thinkwide.data.exchange;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MFFileDown {

    public static void prepareDownExcelFile(HttpServletResponse response, String fileName) throws Throwable {
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));
    }

    public static void prepareDownFile(HttpServletResponse response, String fileName) throws Throwable {
        response.reset();
        response.setContentType("application/x-msdownload");
        //response.setContentLength((int)stream.);
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));
    }


    public static void downFile(HttpServletResponse response, String filePath, String fileName) throws Throwable {

        response.reset();
        File file = new File(filePath);

        response.setContentType("application/x-msdownload");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));

        FileInputStream fis = new FileInputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

        byte[] buff = new byte[500];
        int bytesRead;
        while (-1 != (bytesRead = fis.read(buff))) {
            bos.write(buff, 0, bytesRead);
        }
        bos.flush();
        bos.close();
        fis.close();
    }

    public static void downFile(HttpServletResponse response, InputStream stream, String fileName) throws Throwable {

        response.reset();

        response.setContentType("application/x-msdownload");
        //response.setContentLength((int)stream. );
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

        byte[] buff = new byte[500];
        int bytesRead;
        while (-1 != (bytesRead = stream.read(buff))) {
            bos.write(buff, 0, bytesRead);
        }
        bos.flush();
        bos.close();
        stream.close();
    }
}
